/**
 * PageUtil.java 2015年12月21日 下午4:39:33
 *
 * Copyright (c) 2010-2061 leying.com, Inc. All rights reserved.
 *
 * @Description TODO
 * @version 3.0
 *
 */
package com.xiake.utils;

import java.util.Iterator;
import java.util.Map;


public class PageUtil {

  public static String transToHtml(String uri, PageInfo pageInfo, Map<String, String> params) {
    StringBuffer url = new StringBuffer(uri).append("?");
    // 生成url
    if (params != null && params.size() > 0) {
      Iterator<String> keys = params.keySet().iterator();
      while (keys.hasNext()) {
        String key = keys.next();
        String value = params.get(key);
        if (value != null && !value.equals("")) {
          if (!url.toString().endsWith("?")) {
            url.append("&");
          }
          url.append(key).append("=").append(value);
        }
      }
    }

    int nowPage = pageInfo.getPageNo();
    int allPage = pageInfo.getAllPage();
    StringBuffer pageSb = new StringBuffer("<ul class=\"am-pagination\"><li");
    // 生成上一页
    if (nowPage < 2) {
      pageSb.append(" class=\"am-disabled\"").append("><a href=\"javascript:;\">«</a></li>");
    } else {
      pageSb.append("><a href=\"").append(url.toString())
          .append(url.toString().endsWith("?") ? "" : "&").append("pageNo=").append(nowPage - 1)
          .append("\">«</a></li>");
    }
    // 生成页码列表
    int startNo = 1;
    int endNo = allPage;
    if (allPage > 5) {
      if (nowPage - startNo > 2) {
        startNo = nowPage - 2;
      }
      if (endNo - startNo > 4) {
        endNo = startNo + 4;
      }
      if (startNo > 1 && endNo - startNo < 4) {
        startNo = endNo - 4;
      }
      if (startNo < 1) {
        startNo = 1;
      }
    }
    for (int i = startNo; i <= endNo; i++) {
      pageSb.append("<li");
      if (i == nowPage) {
        pageSb.append(" class=\"am-active\"");
      }
      pageSb.append("><a href=\"");
      if (i == nowPage) {
        pageSb.append("javascript:;");
      } else {
        pageSb.append(url.toString()).append(url.toString().endsWith("?") ? "" : "&")
            .append("pageNo=").append(i);
      }
      pageSb.append("\">").append(i).append("</a></li>");
    }
    // 生成下一页
    pageSb.append("<li");
    if (nowPage >= allPage) {
      pageSb.append(" class=\"am-disabled\"").append("><a href=\"javascript:;\">»</a></li>");
    } else {
      pageSb.append("><a href=\"").append(url.toString())
          .append(url.toString().endsWith("?") ? "" : "&").append("pageNo=").append(nowPage + 1)
          .append("\">»</a></li>");
    }
    pageSb.append("</ul>");
    return pageSb.toString();
  }
}
